package com.zmn.plat.business.impl.orderconfig.orderstock.plat;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.plat.business.interfaces.orderconfig.orderstock.plat.PlatConfigBService;
import com.zmn.plat.model.entity.orderconfig.orderstock.plat.PlatConfig;
import com.zmn.plat.model.entity.orderconfig.orderstock.plat.PlatConfigQuery;
import com.zmn.plat.services.interfaces.orderconfig.oderstock.plat.PlatConfigService;

/**
 * 描述: 平台配置基础接口类
 *
 * @author xiangjunming
 * @since 2020-03-17 10:29:08
 **/
@Service
public class PlatConfigBServiceImpl implements PlatConfigBService {

    /**
     * 无限量库存
     */
    public static final int DEFAULT_STOCK = -1;

    /**
     * 默认系数为1
     */
    public static final double DEFAULT_COEFFICIENT = 1d;

    @Autowired
    PlatConfigService platConfigService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchSet(List<PlatConfig> list, String operator) {
        PlatConfig platConfig = list.get(0);
        Integer plat = platConfig.getPlat();
        PlatConfigQuery query = new PlatConfigQuery();
        query.setPlat(plat);
        Map<String, PlatConfig> platConfigMap = platConfigService.listByQuery(query).stream().collect(Collectors.toMap(item -> item.getServCategId().toString(), item -> item, (p, u) -> p));

        List<PlatConfig> modifyList = Lists.newArrayList();
        list.forEach(item -> {
            if (item.getStock() == null) {
                item.setStock(DEFAULT_STOCK);
            }
            if (item.getCoefficient() == null) {
                item.setCoefficient(DEFAULT_COEFFICIENT);
            }
        });
        List<PlatConfig> insertList = list.stream().filter(item -> {
            PlatConfig exists = platConfigMap.get(item.getServCategId().toString());
            if (exists == null) {
                return true;
            }
            item.setId(exists.getId());
            modifyList.add(item);
            return false;
        }).peek(item -> {
            item.setStatus(GlobalConsts.YES);
            item.setCreater(operator);
            item.setCreateTime(DateUtil.getNow());
            item.setUpdater(operator);
            item.setUpdateTime(DateUtil.getNow());
        }).collect(Collectors.toList());

        if (insertList.size() > 0) {
            platConfigService.insertBatch(insertList);
        }

        if (modifyList.size() > 0) {
            for (PlatConfig s : modifyList) {
                s.setUpdater(operator);
                s.setUpdateTime(DateUtil.getNow());
                platConfigService.updateByKey(s);
            }
        }
    }
}
